package com.cloudcentral.controller;

import com.alibaba.cloud.nacos.NacosConfigProperties;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.nacos.api.config.ConfigService;
import com.alibaba.nacos.api.exception.NacosException;
import com.cloudcentral.util.Result;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

/**
 * Create by Administrator
 * 2023/11/24 15:25
 */
@Slf4j
@RestController
@RequestMapping("/config")
@Tag(name = "配置相关")
public class ConfigController {
  private final NacosConfigProperties nacosConfigProperties;
  private final ConfigService configService;

  @Autowired
  public ConfigController(NacosConfigProperties nacosConfigProperties, ConfigService configService) {
    this.nacosConfigProperties = nacosConfigProperties;
    this.configService = configService;
  }

  @GetMapping("/get")
  @Operation(summary = "获取配置", parameters = {
      @Parameter(name = "type", description = "配置类型", example = """
          modem-type: 解码方式;
          power-level: 功率等级;
          """),
  })
  public Result<Object> get(@RequestParam(required = false) String type) throws NacosException {
    String json = configService.getConfig("json-config", nacosConfigProperties.getGroup(), 5000);
    JSONObject jsonObject = JSON.parseObject(json);
    return Result.ok(StringUtils.isBlank(type) ? jsonObject : jsonObject.get(type));
  }
}
